<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择群" prop="groupId">
        <el-col :span="10">
          <el-form-item prop="groupId">
            <el-select v-model="queryParams.groupId" placeholder="请选择"
                       style="width: 180px" @change="handleQuery">
              <el-option
                  v-for="dict in userGroups"
                  :key="dict.id"
                  :label="dict.groupName"
                  :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="时间">
        <el-col :span="15">
          <el-date-picker
              v-model="queryParams.findTime"
              type="daterange"
              @change="handleQuery"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="对局内容" prop="txtBout">
        <el-input
            v-model="queryParams.txtBout"
            placeholder="请输入对局内容：格龙胜软x*2"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="赢家名称" prop="winName">
        <el-input
            v-model="queryParams.winName"
            placeholder="请输入赢家名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="输家名称" prop="loseName">
        <el-input
            v-model="queryParams.loseName"
            placeholder="请输入输家名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">清空</el-button>
      </el-form-item>
    </el-form>

    <!--    <el-row :gutter="10" class="mb8">-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--            type="primary"-->
    <!--            plain-->
    <!--            icon="Plus"-->
    <!--            @click="handleAdd"-->
    <!--            v-hasPermi="['group:boutRecord:add']"-->
    <!--        >新增-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--            type="success"-->
    <!--            plain-->
    <!--            icon="Edit"-->
    <!--            :disabled="single"-->
    <!--            @click="handleUpdate"-->
    <!--            v-hasPermi="['group:boutRecord:edit']"-->
    <!--        >修改-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--            type="danger"-->
    <!--            plain-->
    <!--            icon="Delete"-->
    <!--            :disabled="multiple"-->
    <!--            @click="handleDelete"-->
    <!--            v-hasPermi="['group:boutRecord:remove']"-->
    <!--        >删除-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--            type="warning"-->
    <!--            plain-->
    <!--            icon="Download"-->
    <!--            @click="handleExport"-->
    <!--            v-hasPermi="['group:boutRecord:export']"-->
    <!--        >导出-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    <!--    </el-row>-->

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="id" align="center" prop="id" />-->
      <!--      <el-table-column label="录入记录id" align="center" prop="refId" />-->
      <el-table-column label="群id" align="center" prop="groupId"/>
      <el-table-column label="录入时间" align="center" prop="createTime" width="120px">
        <template #default="scope">
          {{format(scope.row.createTime, 'yyyy-MM-dd')}}
        </template>
      </el-table-column>
      <el-table-column  label="对局内容" align="center" prop="txtBout"  :tooltip-formatter="(row) => `<h1 style='white-space: pre-wrap;'>${row.txtBout}</h1>`"/>
      <el-table-column label="赢家名称" align="center" prop="winName"/>
      <el-table-column label="输家名称" align="center" prop="loseName"/>
      <el-table-column label="赢家得分" align="center" prop="winScore"/>
      <el-table-column label="输家得分" align="center" prop="loseScore"/>
      <el-table-column label="对局类型：1:单打，2:双打，3:3v3" align="center">
        <template #default="scope">
          <dict-tag :options="group_bout_type" :value="scope.row.boutType"/>
        </template>
      </el-table-column>
      <el-table-column label="奖励金币" align="center" prop="awardCoin"/>
      <!--      <el-table-column label="租户编号" align="center" prop="tenantId" />-->
      <!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template #default="scope">-->
      <!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['group:boutRecord:edit']">修改</el-button>-->
      <!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['group:boutRecord:remove']">删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改单局详情对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="录入记录id" prop="refId">
          <el-input v-model="form.refId" placeholder="请输入录入记录id"/>
        </el-form-item>
        <el-form-item label="选择群" prop="groupId" disabled="groupId.value?true:false">
          <el-col :span="12">
            <el-form-item prop="groupId">
              <el-select v-model="form.groupId" placeholder="请选择"  :disabled="form.id>0 || queryParams.groupId>0">
                <el-option
                    v-for="dict in userGroups"
                    :key="dict.id"
                    :label="dict.groupName"
                    :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="对局内容：格龙胜软x*2" prop="txtBout">
          <el-input v-model="form.txtBout" placeholder="请输入对局内容：格龙胜软x*2"/>
        </el-form-item>
        <el-form-item label="赢家名称" prop="winName">
          <el-input v-model="form.winName" placeholder="请输入赢家名称"/>
        </el-form-item>
        <el-form-item label="输家名称" prop="loseName">
          <el-input v-model="form.loseName" placeholder="请输入输家名称"/>
        </el-form-item>
        <el-form-item label="赢家得分" prop="winScore">
          <el-input v-model="form.winScore" placeholder="请输入赢家得分"/>
        </el-form-item>
        <el-form-item label="输家得分" prop="loseScore">
          <el-input v-model="form.loseScore" placeholder="请输入输家得分"/>
        </el-form-item>
        <el-form-item label="奖励金币" prop="awardCoin">
          <el-input v-model="form.awardCoin" placeholder="请输入奖励金币"/>
        </el-form-item>
        <el-form-item label="是否删除" prop="deleted">
          <el-input v-model="form.deleted" placeholder="请输入是否删除"/>
        </el-form-item>
        <el-form-item label="租户编号" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入租户编号"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import * as boutRecordServer from "@/api/group/boutRecord.js";

const {proxy} = getCurrentInstance();
const {group_bout_type} = proxy.useDict("group_bout_type");

const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
import {AES_Decrypt} from "@/utils/jsencrypt.js";

const route = useRoute();
const importId = ref(AES_Decrypt(route.query.importId));
import * as groupServer from "@/api/group/group.js";
import {format} from "date-fns";

const groupId = ref(Number(AES_Decrypt(route.query.groupId)) === 0 ? undefined : Number(AES_Decrypt(route.query.groupId)));
const resetFlag = ref(false);
const userGroups = ref([])
const data = reactive({
  form: {},
  queryParams: {
    orderByColumn: 'create_time',
    isAsc: 'desc',
    pageNum: 1,
    pageSize: 30,
    startTime: null,
    findTime: null,
    endTime: null,
    refId: importId.value,
    groupId: groupId.value,
    txtBout: null,
    winName: null,
    loseName: null,
    winScore: null,
    loseScore: null,
    boutType: null,
    awardCoin: null,
    tenantId: null,
  },
  rules: {
    refId: [
      {required: true, message: "录入记录id不能为空", trigger: "blur"}
    ],
    groupId: [
      {required: true, message: "群id不能为空", trigger: "blur"}
    ],
    txtBout: [
      {required: true, message: "对局内容：格龙胜软x*2不能为空", trigger: "blur"}
    ],
    winName: [
      {required: true, message: "赢家名称不能为空", trigger: "blur"}
    ],
    loseName: [
      {required: true, message: "输家名称不能为空", trigger: "blur"}
    ],
    winScore: [
      {required: true, message: "赢家得分不能为空", trigger: "blur"}
    ],
    loseScore: [
      {required: true, message: "输家得分不能为空", trigger: "blur"}
    ],
    boutType: [
      {required: true, message: "对局类型：1:单打，2:双打，3:3v3不能为空", trigger: "change"}
    ],
    awardCoin: [
      {required: true, message: "奖励金币不能为空", trigger: "blur"}
    ],
    createTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
    updateTime: [
      {required: true, message: "更新时间不能为空", trigger: "blur"}
    ],
    deleted: [
      {required: true, message: "是否删除不能为空", trigger: "blur"}
    ],
    tenantId: [
      {required: true, message: "租户编号不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);
const start = (() => {
  return new Promise(resolve => {
    groupServer.callFindList(null).then(res => {
      userGroups.value = res.data
      //console.log(!groupId.value);
      //console.log(groupId.value);
      //console.log(queryParams.value.groupId );
      if (!groupId.value && !resetFlag.value) {
        userGroups.value.forEach(item => {
          if (item.loginDefault === 1) {
            groupId.value = item.id
            queryParams.value.groupId = item.id
          }
        })
      }
      if (!groupId.value && !resetFlag.value) {
        groupId.value = userGroups.value[0].id
        queryParams.value.groupId = userGroups.value[0].id
      }
    }).then(() => {
      // //console.log("start",currentAdmin.value)
      resolve()
    })
  })
})

/** 查询单局详情列表 */
function getList() {
  loading.value = true;
  start().then(() => {
    if (queryParams.value.findTime) {
      queryParams.value.endTime = queryParams.value.findTime[1]
      queryParams.value.startTime = queryParams.value.findTime[0]
    }
    boutRecordServer.listRecord(queryParams.value).then(response => {
      recordList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单清空
function reset() {
  form.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    id: null,
    refId: null,
    groupId: null,
    txtBout: null,
    winName: null,
    loseName: null,
    winScore: null,
    loseScore: null,
    boutType: null,
    awardCoin: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    tenantId: null,
    remark: null
  };
  proxy.resetForm("recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 清空按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value = {
    orderByColumn: 'create_time',
    isAsc: 'desc',
    pageNum: 1,
    pageSize: 30,
    startTime: null,
    findTime: null,
    endTime: null,
    refId: null,
    groupId: null,
    txtBout: null,
    winName: null,
    loseName: null,
    winScore: null,
    loseScore: null,
    boutType: null,
    awardCoin: null,
    tenantId: null,
  };
  resetFlag.value=true
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加单局详情";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]
  boutRecordServer.getRecord({id: _id}).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改单局详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        boutRecordServer.updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        boutRecordServer.addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id ? [row.id] : ids.value;

  proxy.$modal.confirm('是否确认删除单局详情编号为"' + _ids + '"的数据项？').then(function () {
    return boutRecordServer.delRecord({delIds: _ids});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('group/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}

getList();
</script>
